import json

import smtplib

from email.mime.text import MIMEText

import time

from email.mime.multipart import MIMEMultipart


# 协程库
import asyncio

import jwt

# 导入短信模块
from qcloudsms_py import SmsSingleSender

# 腾讯云指定异常
from qcloudsms_py.httpclient import HTTPError

# ssl证书
import ssl

# 导入随机数
import random

#设置证书
ssl._create_default_https_context = ssl._create_unverified_context


from db import MyMongo

import datetime

import redis


# 聊天记录类
class Chat:

	def __init__(self):

		self.r = redis.Redis(decode_responses=True)


	# 入队操作
	def push(self,key,msg):

		if self.r.exists(key) and msg != "":

			self.r.lpush(key,msg)

		else:

			self.r.lpush(key,msg)

			self.r.expire(key,300)



	# 获取所有聊天记录
	def get(self,key):

		return self.r.lrange(key,0,-1)


# 图集类
class ImgList:

	def __init__(self):

		self.mymongo = MyMongo("img")


	# 删除图集
	def del_img(self,sid):

		self.mymongo.remove({"sid":sid})

	# 获取图集
	def get_img(self,sid):

		res = self.mymongo.find_one({"sid":sid})

		if res is None:
			return []
		else:
			return res["imglist"]

	# 插入图集
	def insert_one(self,sid,imglist):

		self.mymongo.insert({"sid":sid,"imglist":imglist})

	# 修改图集
	def update_one(self,sid,imglist):

		self.mymongo.update_one({"sid":sid},"imglist",imglist)


# imglist = ImgList()

# print(imglist.insert_one(5,["http://localhost:8888/static/touxiang.png","http://localhost:8888/static/touxiang.png"]))







# 用户关注类

class Flow:

	# 初始化方法
	def __init__(self):

		self.r = redis.Redis(decode_responses=True,charset="utf-8",encoding="utf-8")

	# 查看是否有关注
	def if_flow(self,uid,fuid):

		res = self.r.hexists(uid,fuid)

		return res

	# 设置关注

	def set_flow(self,uid,fuid,fusername):

		self.r.hset(uid,fuid,fusername)

	# 取消关注
	def del_flow(self,uid,fuid):

		self.r.hdel(uid,fuid)

	# 获取关注人id
	def get_flow(self,uid):

		return self.r.hkeys(uid)

	# 获取关注人用户名
	def get_username(self,uid):

		return self.r.hvals(uid)

# flow = Flow()



# print(flow.get_flow("50"))

# print(flow.get_username("50"))




# 短信类
class SendSms:


	def get_code(self):

		mystr = ""
		for x in range(4):
			mystr += str(random.randint(0,9))
		return mystr	

	def __init__(self):

		# 应用id appid
		self.appid = 1400590057

		# 应用密钥
		self.appkey = 'bfa928250db600e75cb596f6319b32e1'

		# 短信模板
		self.template_id = 1175459

		# 短信签名
		self.sms_sign = "python面试总结"


	def send_sms(self,phone):

		# 实例化对象
		mysms = SmsSingleSender(self.appid,self.appkey)

		# 通配符模板变量

		code = self.get_code()

		params = [code]

		# 入库操作
		mymongo = MyMongo()

		mymongo.insert({"datetime":datetime.datetime.now(),"code":code,"phone":phone})

		try:

			# 国际区号
			mysms.send_with_param(86,phone,self.template_id,params,sign=self.sms_sign,extend="",ext="")
		except HTTPError as e:
			print(str(e))
		except Exception as e:
			print(str(e))

# 实例化对象
# sendsms = SendSms()

# sendsms.send_sms("15531613177")





# 令牌方法
class MyJwt:

	# 加密
	def encode(self,userinfo):

		encode_str = jwt.encode(userinfo,'123',algorithm="HS256")

		try:
			encode_str = str(encode_str,"utf-8")
		except Exception as e:
			pass
		return encode_str

	# 解密
	def decode(self,jwt_str):

		return jwt.decode(jwt_str,'123',algorithms=['HS256'])


# myjwt = MyJwt()

# print(myjwt.encode({"id":16}))

# print(myjwt.decode(myjwt.encode({"id":16})))



# 封装邮箱发送

async def send_mail(to,title,content,id):

	print("开始执行")

	for x in range(5):

		print("耗费了%s秒" % x)
		time.sleep(1)

	print("发送邮件")

	return "发送邮件成功"

	# # 发送者
	# _user = "你的邮箱地址"

	# # smtp密钥
	# _pwd = "您刚申请的密钥"

	# # 发送设置
	# msg = MIMEMultipart()
	# msg["Subject"] = title
	# msg["From"] = _user
	# msg["To"] = to

	# # 加密操作
	# myjwt = MyJwt()
	# id = myjwt.encode({"id":id})

	# # 邮件内容
	# mail = MIMEText("请您点击超链接进行激活<a href='http://locallhost:8888/active/?id=%s'>激活账号</a>" % id,"html","utf-8")
	# msg.attach(mail)

	# # 调用
	# s = smtplib.SMTP_SSL("smtp.qq.com",465)

	# # 登录腾讯邮箱
	# s.login(_user,_pwd)

	# # 目标发送
	# s.sendmail(_user,to,msg.as_string())

	# # 关闭协议
	# s.close()




# asyncio.run(send_mail("123","123","123","123"))

# 声明事件循环
# loop = asyncio.get_event_loop()
# # 在事件循环中调用异步方法
# res = loop.run_until_complete(send_mail("123","123","123","123"))
# print(res)
# # 手动关闭事件循环
# loop.close()




def ret_json(mydict):

	ret = json.dumps(mydict,ensure_ascii=False,default=str,indent=4)

	return ret